<template>
  <div></div>
</template>

<script setup lang="ts">
import { ref, reactive, inject, computed, watch, onMounted, onBeforeUnmount } from 'vue';
import { getCloudFileHref } from '@/utils/index'
import { getEventCount } from '@/utils/api';
import { getStaticFile } from '@sutpc/axios';
import { useUserStore } from '@/store/user';

defineOptions({
  name: 'GlobalLayer'
})

// interface LayerItem {
//   type: string;
//   code: string;
//   url: string;
//   properties?: string;
// }

// interface PropsType {
//   layerData: LayerItem
// }
// const props = withDefaults(defineProps<PropsType>(), {})

const main = inject<any>('main');
const { mapInstance }: any = main;


const userStore = useUserStore()

let layer: any;
const EVENT_HANDLER  = 'TIAN-POLYGON-PICK'
// 绘制坪山区域polygon
const getPingshan = async () => {
  if (mapInstance.value) {
    const jsonData = await getStaticFile('[publicPath]static/jsons/geojson.json')
    const coordinates = jsonData.features[0].geometry.coordinates[0]
      let psPolygon = {
        id: 'tianan-pingshan-polygon',
        groupId: 'tianan-pingshan-polygon',
        coordinates,
        coordinateType: 1, //坐标系类型，取值范围：0为Projection类型，1为WGS84类型，2为火星坐标系(GCJ02)，3为百度坐标系(BD09)，默认值：0
        range: [1, 100000], //可视范围：[近裁距离, 远裁距离]，取值范围: [任意负值, 任意正值]
        color: [0.13, 0.65, 0.73, 0.8], //多边形的填充颜色
        frameColor: '#ffffff', //边框颜色
        frameThickness: 50, //边框厚度
        intensity: 100, //亮度
        style: PolygonStyle.SingleColor, //单色 请参照API开发文档选取枚举
        depthTest: false //是否做深度检测 开启后会被地形高度遮挡
      }
      let pArr = [];
      pArr.push(psPolygon);
      const res = await mapInstance.value.acApi.polygon.add(pArr)
      mapInstance.value.acApi.polygon.focus('tianan-pingshan-polygon', 10000);
      userStore.isShowMenu(false)
  }
}
// 删除坪山区域polygon
const deletePsPolygon = async () => {
  await mapInstance.value.acApi.polygon.delete('tianan-pingshan-polygon')
}

if (mapInstance.value){
  mapInstance.value.mapClass.EventClass.addEventByKey(EVENT_HANDLER  , async (e) => {
    // 定位路口显示路口设备
    if (e.GroupID === 'tianan-pingshan-polygon') {
      deletePsPolygon()
      // 定位指定路口，同时显示顶部路口设备模块
      await mapInstance.value.acApi.camera.set(536491.8625, 2510202.08, 9000, -83.974602, -114.262474)
      userStore.setShowLayer1In(true)
      // 显示实时路况
      addWmsLayer()
      // 显示交通事件
      getRoadEventCount()
    }
  })
}

// 监听全局态势三种情况：globalType=1实时路况，=2交通流量，=3交通事件
const globalType = computed(() => {
  return userStore.$state.globalType
})
watch(() => globalType.value, (newVal) => {
  clearWmsLayer()
  if (newVal === 1) {
    addWmsLayer()
  }
  if (newVal === 2) {
    addWmsLayer()
  }
  if (newVal === 3) {
    getRoadEventCount()
  }
})

// 1实时路况，逻辑部分
// 路网图层数据
const trafficConditionWMSAMLayerData = reactive({
  type: 'wms',
  code: 'traffic-condition-am',
  dataOrigin: 'geoserver',
  url: 'http://10.9.101.36:10006/geoserver/ps/wms?service=WMS&version=1.1.0&request=GetMap&layers=ps%3Aps_real_link_status4547&bbox=527536.539092678%2C2503570.39281185%2C544665.030709622%2C2520275.55681067&width=768&height=749&srs=EPSG%3A4547&format=application/openlayers'
  // url: '/req/tesp-layer/geoserver/tesp/wms?service=WMS&version=1.1.0&request=GetMap&layers=cim_highway_abudhabi_02am&bbox={bbox-epsg-32640}&width=256&height=256&srs=EPSG:32640&styles=&format=image%2Fpng&TRANSPARENT=true'
});

// 增加wms图层实时路况
const addWmsLayer = async () => {
  if (mapInstance.value){
    await mapInstance.value.acApi.camera.set(536491.8625, 2510202.08, 1000, -83.974602, -114.262474)
    await mapInstance.value.mapClass.LayerClass.addWmsLayer([{
      id:"462",
      url: 'http://10.9.100.82:8899/geoserver/ps/wms?service=WMS&version=1.1.0&request=GetMap&layers=ps_real_link_status4547&bbox={bbox-epsg-4547}&width=256&height=256&srs=EPSG:4547&styles&format=image%2Fpng&TRANSPARENT=true',
      xmlPath: 'http://10.9.100.82:8899/geoserver/ps/wms?service=WMS&request=GetCapabilities&version=1.1.1',//必选，xml协议的url路径
      layerName: "ps_real_link_status4547",//必选，图层名称
      tileMatrixName: 'EPSG:4547',//必选，如果服务类型是WMTS：tileMatrixName是切片方案，如果服务类型是WMS：tileMatrixName是坐标类型
      ogcEPSG: 'EPSG:4547',//必选，坐标系类型
    }])
    // console.log('绘制实时路况')
  }
}

// 删除wms图层
const clearWmsLayer = async () => {
  if (mapInstance.value){
    await mapInstance.value.mapClass.LayerClass.removeWmsLayer([trafficConditionWMSAMLayerData])
    // console.log('删除实时路况')
  }
}

// 2交通流量，逻辑部分

// 3交通事件，逻辑部分
const drawEventMarkers = (data) => {
  const arr = []
  console.log(getCloudFileHref('images/jtsjIcon.png'))
  data.forEach((item) => {
    let obj = {
      id: item.code,
      groupId: item.code,
      coordinate: [item.lng, item.lat, 0],//坐标位置
      coordinateType: 1,//默认0是投影坐标系，也可以设置为经纬度空间坐标系值为1
      anchors: [-25, 50],//锚点，设置Marker的整体偏移，取值规则和imageSize设置的宽高有关，图片的左上角会对准标注点的坐标位置。示例设置规则：x=-imageSize.width/2，y=imageSize.height
      imageSize: [106, 116],//图片的尺寸
      hoverImageSize: [106, 116],//鼠标悬停时显示的图片尺寸
      range: [1, 10000],//可视范围
      imagePath: 'http://10.9.101.36:10005/static/images/shijian.png',//显示图片路径
      // hoverImagePath: HostConfig.Path + '/samples/images/hilightarea.png',// 鼠标悬停时显示的图片路径
      fixedSize: true,//图片固定尺寸，取值范围：false 自适应，近大远小，true 固定尺寸，默认值：false 
      priority: 0,//避让优先级
      text: `交通事件 ${item.num}`,//显示的文字 
      useTextAnimation: false,//关闭文字展开动画效果 打开会影响效率
      textRange: [1, 10000],//文本可视范围[近裁距离, 远裁距离]
      textOffset: [0, 0],// 文本偏移
      textBackgroundColor: Color.SpringGreen,//文本背景颜色
      fontSize: 24,//字体大小
      fontOutlineSize: 1,//字体轮廓线大小
      fontColor: Color.White,//字体颜色
      fontOutlineColor: Color.Black,//字体轮廓线颜色

      popupURL: 'http://10.9.101.36:10005/static/popup/vehicleMarkerPopup.html',//弹窗HTML链接
      popupBackgroundColor: [1.0, 1.0, 1.0, 0.5],//弹窗背景颜色
      popupSize: [300, 300],//弹窗大小
      popupOffset: [0, 0],//弹窗偏移

      showLine: false,//标注点下方是否显示垂直牵引线
      // lineSize: [2, 100],//垂直牵引线宽度和高度[width, height]
      // lineColor: Color.SpringGreen,//垂直牵引线颜色
      // lineOffset: [0, 0],//垂直牵引线偏移

      autoHidePopupWindow: true,//失去焦点后是否自动关闭弹出窗口
      autoHeight: false,// 自动判断下方是否有物体
      displayMode: 4,//智能显示模式  开发过程中请根据业务需求判断使用四种显示模式 
      clusterByImage: true,// 聚合时是否根据图片路径分类，即当多个marker的imagePath路径参数相同时按路径对marker分类聚合
      
      occlusionCull: false//是否参与遮挡剔除
    }
    arr.push(obj)
  })
  console.log(arr);
  return arr
}

// 获取路口事件接口
const getRoadEventCount = () => {
  getEventCount().then((res) => {
    console.log(res)
    const resData = res
    if (resData.length !== 0) {
      var eventmarker = drawEventMarkers(resData);
      mapInstance.value.acApi.marker.add(eventmarker)
      // mapInstance.value.acApi.marker.add(markerTemp)
    }
  })
}

const layer1In = computed(() => {
  return userStore.getShowLayer1In
})

const layerType = computed(() => {
  return userStore.getLayerType
})
// 监听点击全局态势监测按钮，返回坪山全域地图
watch(() => layer1In.value, (newVal) => {
  if (!newVal && layerType.value === 'globalModel') {
    getPingshan()
  }
})

onMounted(() => {
  getPingshan()
})

onBeforeUnmount(() => {
  if(mapInstance.value) {
    mapInstance.value.mapClass.EventClass.removeEventByKey(EVENT_HANDLER);
    deletePsPolygon()
    clearWmsLayer()
    userStore.setGlobalType(0)
    userStore.setShowLayer1In(false)
    try {
      layer.closePopup && layer.closePopup()
    } catch (error) {}
  }
})
</script>

<style lang="less" scoped></style>